package com.tzinfo.tzb.util;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

/**
 * Created by tongwanglin on 14-1-2.
 */
public class CacheManager {
	private Context mContext;

	public CacheManager(Context context) {
		mContext = context;
	}

	public String getCache(String name) {
		String json = null;
		try {
			FileInputStream inputStream = mContext.openFileInput(name
					+ ".json");
			if (inputStream != null) {
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				byte[] buffer = new byte[1024];
				int length = -1;
				while ((length = inputStream.read(buffer)) != -1) {
					stream.write(buffer, 0, length);
				}
				json = stream.toString();
				stream.close();
			}
			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json;
	}


	public static String JSONTokener(String in) {
		// consume an optional byte order mark (BOM) if it exists
		if (in != null && in.startsWith("\ufeff")) {
			in = in.substring(1);
		}
		if (in != null && in.endsWith(",]")) {
			in = in.substring(0, in.length() - 2) + "]";
		}
		return in;
	}

	public void updateCache(String name, String content) {
		try {
			FileOutputStream outputStream = mContext.openFileOutput(name
					+ ".json", Context.MODE_WORLD_READABLE);
			outputStream.write(content.getBytes());
			outputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
